package org.zsl.dao;

import org.zsl.model.User;

import java.sql.*;
import java.util.List;

public class UserDAO implements IUserDAO {

    private Connection connection = null;

    private Statement statement = null;
    private PreparedStatement preparedStatement = null;

    private ResultSet resultSet = null;


    private String url = "jdbc:mysql://127.0.0.1:3306/demo";
    private String username = "root";
    private String password = "123456";


    public UserDAO() {

        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // 注册驱动
            connection = DriverManager.getConnection(url, username, password);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    /**
     *  String.format
     * */
    @Override
    public Boolean insert(User user) {
        String sql = "insert into user(username,password,role_id) value(?,?,?)";
        Boolean flag =false;


        try {
            preparedStatement=    connection.prepareStatement(sql);
            preparedStatement.setString(1,user.getUsername());
            preparedStatement.setString(2,user.getPassword());
            preparedStatement.setInt(3,user.getRoleId());

         flag=     preparedStatement.executeUpdate()>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

      return  flag;
    }

    @Override
    public Boolean delete(Integer userId) {
        return null;
    }

    @Override
    public Boolean update(User user) {
        return null;
    }

    @Override
    public ResultSet selectAll() {
        String sql = "select * from user"; //1

        try {
            statement = connection.createStatement(); //2
            resultSet = statement.executeQuery(sql); //3
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return resultSet; //4
    }

    @Override
    public List<User> selectAll2() {
        return null;
    }
}
